package cn.tdeu.v4;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 *
 *
 *
 *
 *
 *
 *
 */
public class Client {
    private Socket socket;
    private static final String HOST="172.20.11.33";
    private static Integer PORT=3678;
    private String ip;
    private BufferedReader br;

      public Client(){
        try {
            //私有化socket--返回socket【不能省】
            socket=new Socket(HOST,PORT);
            ip=socket.getInetAddress().getHostAddress();
        } catch (SocketException e){
            System.out.println("客户端链接被重置");
        }catch (UnknownHostException e){
            System.out.println("IP地址有问题，请询问客户端！");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开链接");
        }
    }
    public void start(){
        PrintWriter pw=null;
        try {
            br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));
            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

            new Thread(()->{
                try {
                    String message;
                    while((message= br.readLine())!=null){
                        System.out.println("服务器端说"+message);
                    }
                } catch (IOException e) {
                    System.out.println("服务器端发来的消息断开了~~");
                } finally {
                    if (br!=null)
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }).start();
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String say = input.nextLine();
                pw.println(ip+"客户端说："+say);
            }

        }catch (UnsupportedEncodingException e){
            System.out.println("客户端与服务器端，字符集不一致！");
        }catch (IOException e) {
            System.out.println("客户端断开了链接！");
        } finally {
            //关闭流   关闭socket
            if (pw != null)
                pw.close();
            try {
                if (br!=null)
                    br.close();
            } catch (IOException e) {
                System.out.println("输出流断开链接");
            }
            if(socket!=null&&!socket.isClosed()){
                System.out.println("客户端关闭成功！success~");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            }
        }
    }

    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }

}
